package tubesrus.servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import tubesrus.beans.MailManager;
import tubesrus.beans.Md5;
import tubesrus.beans.Utilisateur;
import tubesrus.beans.Video;
import tubesrus.beans.myStateless;



public class Dispatcher extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@EJB myStateless s;

	public Dispatcher() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action=request.getParameter("action");
		String dispatchTo="accueil.jsp";
		
		//action called to create a new user
		if(action.equals("newUser"))
		{
			String id = request.getParameter("id");
			String email = request.getParameter("email");
			String pass = Md5.encode(request.getParameter("password"));
			String sexe = request.getParameter("sexe");
			String nom = request.getParameter("nom");
			String prenom = request.getParameter("prenom");
			s.creerUtilisateur(id, email, pass, sexe, nom, prenom);
			MailManager m = new MailManager();
			m.sendConfirmation(id, email);
			dispatchTo="confirmation.jsp?id="+id;
			request.getRequestDispatcher(dispatchTo).forward(request, response);
		}
		
		//action called to disconnect a user (disconnects all sessions)
		if(action.equals("disconnect"))
		{
			Cookie[] cookies = ((HttpServletRequest) request).getCookies();
	    	if (cookies != null) {
				for(int i=0; i<cookies.length; i++) {
					Cookie cookie = cookies[i];
					if (cookie.getName().equals("id"))	{
						cookie.setMaxAge(0);
						response.addCookie(cookie);
					}
					if (cookie.getName().equals("pass"))	cookie.setMaxAge(0);
				}
			}
	    	HttpSession session = request.getSession();
			session.invalidate();
			response.sendRedirect("");
		}
		
		if(action.equals("viewVideos"))
		{
			String id = request.getParameter("id");
			ArrayList<Video> videos = s.getVideos();
			Utilisateur user = s.findByUid(id);
			request.setAttribute("videos", videos);
			request.setAttribute("user", user);
			dispatchTo="videos.jsp";
			request.getRequestDispatcher(dispatchTo).forward(request, response);
		}

		if(action.equals("viewProfil"))
		{
			String id = request.getParameter("id");
			Utilisateur u = null;
			if(id != null) {
				u = s.findByUid(id);
				request.setAttribute("user",u);
			}
			dispatchTo="profil.jsp";
			request.getRequestDispatcher(dispatchTo).forward(request, response);
		}
		
		if(action.equals("confirmation"))
		{
			String id = (String) request.getParameter("id");
			String code = (String) request.getParameter("code");
			if(Md5.encode(id+"_confirmation").equals(code)) {
				s.update(id, "statut", "utilisateur");
				response.sendRedirect("");
			} else {
				response.sendRedirect("confirmation.jsp?id="+id+"?error=true"); //TODO Erreur de code de confirmation
			}
		}
		

		if(action.equals("postComment"))
		{
			String texte = (String) request.getParameter("texte");
			String user = (String) request.getParameter("user");
			String videoId = (String) request.getParameter("videoId");
			System.out.println("user : " + user + ", texte : " + texte );
			s.creerCommentaire(texte, user, videoId);
			s.findByUid(user).incNbComm();
			response.sendRedirect("");

		}

		if(action.equals("viewUsers"))
		{
			request.setAttribute("users", s.getUtilisateurs());
			dispatchTo="utilisateurs.jsp";
			request.getRequestDispatcher(dispatchTo).forward(request, response);

		}
		
		if(action.equals("viewVideo"))
		{
			Video v = s.getVideo(Long.parseLong(request.getParameter("id_video")));
			String url = v.getUrl();
			request.setAttribute("comments", s.getCommentaires(v.getId().toString()));
			request.setAttribute("url", url);
			dispatchTo="video.jsp";
			request.getRequestDispatcher(dispatchTo).forward(request, response);
		}
		
		if(action.equals("achatVideo"))
		{
			String id = request.getParameter("id");
			String id_video = request.getParameter("id_video");
			Video v =  s.getVideo(Long.parseLong(id_video));
			Utilisateur user = s.addVideoToUser(id, Long.parseLong(id_video));
			ArrayList<Video> videos = s.getVideos();
			Integer i = (Integer)user.getVidz()-v.getPrix();
			s.update(user.getId(), "vidz", i.toString());
			request.setAttribute("user", user);
			request.setAttribute("videos", videos);
			Utilisateur auteur = s.findByName(v.getAuteur());
			i = (Integer)auteur.getVidz()+v.getPrix();
			s.update(auteur.getId(), "vidz", i.toString());
			dispatchTo="videos.jsp";
			request.getRequestDispatcher(dispatchTo).forward(request, response);
		}

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

}